<template>

  <div>

    <!-- topic-->
    <el-card class="box-card" v-if="specificPermissions.includes('查询')">
      <!-- 1.搜索框-->
      <el-form :model="form" ref="form">
        <el-row style="margin-bottom: 2px;">
          <el-col :span="5" class="flex-container">
            <div class="search-label">员工姓名：</div>
            <div class="search-input">
              <el-input v-model="form.searchText" @input="getEmployees" placeholder="输入关键字搜索"></el-input>
            </div>
          </el-col>
          <el-col :span="9" class="flex-container">
            <div class="search-label">日期范围：</div>
            <div class="search-input">
              <el-date-picker
                  v-model="form.dateRange"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  align="right"
                  @input="getEmployees"
              ></el-date-picker>
            </div>
          </el-col>
          <el-col :span="5" class="flex-container">
            <div class="search-label">状态：</div>
            <div class="search-input">
              <el-select v-model="form.statusFilter" placeholder="状态" @change="getEmployees">
                <el-option label="查询所有" value=""></el-option>
                <el-option label="开启" value="0"></el-option>
                <el-option label="禁用" value="1"></el-option>
              </el-select>
            </div>
          </el-col>
          <el-col :span="2">
            <el-button type="primary" @click="getEmployees">搜索</el-button>
          </el-col>
          <template>
            <el-col :span="2">
              <el-button
                  v-for="(permission, index) in specificPermissions"
                  :key="index"
                  v-if="permission === '增加'"
                  type="success"
                  @click="showAddModal1()"
              >
                新增员工
              </el-button>
            </el-col>
          </template>
        </el-row>
      </el-form>
      <div>

      </div>
      <!--2.表格数据-->
      <el-table :data="filteredData" stripe>
        <el-table-column prop="id" label="序号" align="center" sortable></el-table-column>
        <el-table-column prop="name" label="姓名" align="center"></el-table-column>
        <el-table-column prop="avatar" label="头像" align="center">
          <template slot-scope="scope">
            <img v-if="scope.row.avatar" :src="scope.row.avatar" alt="头像" width="40px" height="40px">
            <img v-else src="default-avatar.jpg" alt="头像" width="40px" height="40px">
          </template>
        </el-table-column>

        <el-table-column prop="username" label="用户名" align="center"></el-table-column>
        <el-table-column label="拥有角色" align="center" width="200">
          <template slot-scope="scope">
            <el-tag v-for="(role, index) in scope.row.roles" :key="index"
                    type="success">
              {{ role.name }}
            </el-tag>
          </template>
        </el-table-column>


        <el-table-column label="状态" width="100">
          <template slot-scope="scope" v-if="scope.row.id !== 1">
            <el-switch
                v-model="scope.row.status"
                :active-value="0"
                :inactive-value="1"
                active-color="#13ce66"
                inactive-color="#ff4949"
                @change="updateEmployeeStatus(scope.row.id)"
            ></el-switch>
            <span>{{ scope.row.status === 0 ? '开启' : '禁用' }}</span>
          </template>
          <template slot-scope="scope" v-else>
            <!-- 空模板，不显示状态信息 -->
          </template>
        </el-table-column>
        <el-table-column prop="email" label="邮箱" width="200" align="center"></el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="170" sortable>
          <template slot-scope="scope">
            {{ scope.row.createdAt | dateFormat }}
          </template>
        </el-table-column>
        <el-table-column
            v-if="specificPermissions.includes('分配角色') || specificPermissions.includes('修改') || specificPermissions.includes('删除')"
            fixed="right" label="操作" width="300" align="center">
          <template slot-scope="scope">
            <!-- 显示分配角色按钮 -->
            <el-button v-if="specificPermissions.includes('分配角色')" type="primary" size="mini"
                       @click="assignRole(scope.row)">
              <i class="el-icon-setting"></i>
              分配角色
            </el-button>
            <!-- 如果不是第一个，就显示编辑和删除按钮 -->
            <template v-if="scope.row.id !== 1">
              <el-button v-if="specificPermissions.includes('修改')" type="warning" size="mini"
                         @click="editEmployee(scope.row)">
                <i class="el-icon-edit"></i> 编辑
              </el-button>
              <el-button v-if="specificPermissions.includes('删除')" type="danger" size="mini"
                         @click="deleteEmployee(scope.row.id)">
                <i class="el-icon-delete"></i> 删除
              </el-button>
            </template>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[3, 5, 15, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </el-card>
    <el-empty v-else description="你没有查询的权限，无法访问"></el-empty>

    <!-- 3.模态框 -->
    <!--1.分配角色模态框-->
    <div>
      <el-dialog :visible.sync="showRoleModal" title="分配角色" width="30%" custom-class="my-dialog">
        <div v-if="selectedEmployee" class="dialog-content">
          <div>员工姓名： {{ selectedEmployee.name }}</div>
          <div class="role-options">
            <el-checkbox-group v-model="selectedRole">
              <el-checkbox v-for="(role, index) in roles" :key="role.id" :label="role.id"
                           :checked="isRoleSelected(role)"
                           :disabled="index === 0">
                {{ role.name }}
              </el-checkbox>
            </el-checkbox-group>
          </div>
          <div class="dialog-footer">
            <el-button type="primary" @click="saveRole">保存角色分配</el-button>
          </div>
        </div>
      </el-dialog>

      <!--2.编辑角色模态框-->
      <el-dialog title="编辑角色" :visible.sync="showEditModal" width="30%">
        <el-form :model="editEmployeeData" label-width="100px">
          <el-form-item label="员工id" prop="name">
            <el-input v-model="editEmployeeData.id" readonly></el-input>
          </el-form-item>
          <el-form-item label="员工姓名" prop="name">
            <el-input v-model="editEmployeeData.name"></el-input>
          </el-form-item>
          <el-form-item label="用户名" prop="username">
            <el-input v-model="editEmployeeData.username"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editEmployeeData.email"></el-input>
          </el-form-item>
          <el-form-item label="头像" prop="avatar">
            <el-upload
                class="avatar-uploader"
                action="http://localhost:8888/community/employee/uploadImg"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
                name="file"
                v-model="editEmployeeData.avatar"><!-- 指定文件上传参数名 -->
              <img v-if="imageUrl" :src="imageUrl" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
       <el-button @click="showEditModal = false">取 消</el-button>
       <el-button type="primary" @click="saveEmployee">确 定</el-button>
      </span>
      </el-dialog>
      <!--3.新增角色模态框-->
      <el-dialog title="新增角色" :visible.sync="showAddModal" width="30%">
        <el-form :model="addEmployeeData" label-width="100px">
          <el-form-item label="员工姓名" prop="name">
            <el-input v-model="addEmployeeData.name"></el-input>
          </el-form-item>
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addEmployeeData.username"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addEmployeeData.email"></el-input>
          </el-form-item>
          <el-form-item label="头像" prop="avatar">
            <el-upload
                class="avatar-uploader"
                action="http://localhost:8888/community/employee/uploadImg"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
                name="file"
                v-model="addEmployeeData.avatar"><!-- 指定文件上传参数名 -->
              <img v-if="imageUrl" :src="imageUrl" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
    <el-button @click="showAddModal = false">取消</el-button>
    <el-button type="primary" @click="saveAddEmployee">确定</el-button>
  </span>
      </el-dialog>
    </div>

  </div>
</template>

<script>
import {MessageBox} from "element-ui";
import {extractPermissions} from '@/assets/js/helper';

export default {
  data() {
    return {
      specificPermissions: '',
      imageUrl: '',
      addEmployeeData: {}, // 存储新增员工的数据
      showAddModal: false, // 新增模态框
      editEmployeeData: {}, // 存储编辑员工的数据
      showEditModal: false, // 控制编辑员工对话框的显示状态
      showRoleModal: false,
      selectedEmployee: null,
      selectedRole: [], // 存储选中的多个角色
      roles: '',
      form: {
        searchText: '',
        dateRange: [],
        statusFilter: ''
      },
      filteredData: [], // 员工数据
      filteredRoleData: [],
      currentPage: 1, // 当前页码
      pageSize: 5, // 每页显示条数
      total: 0 // 总条数
    };
  },
  mounted() {
    //1.查询员工
    this.getEmployees();

    //2.Search_Role
    this.getRoles();

    // 3. 获取特定ID的权限
    this.specificPermissions = extractPermissions(3);
    console.log("Specific Permissions: ", this.specificPermissions);

  },
  methods: {
    showAddModal1() {
      this.imageUrl = null;
      this.showAddModal = true;
    },

    handleAvatarSuccess(res, file) {
      // 上传成功回调函数
      this.imageUrl = res;

      // 将图片的URL保存在addEmployeeData.avatar
      this.addEmployeeData.avatar = this.imageUrl;
    },
    beforeAvatarUpload(file) {
      // 头像上传前的校验函数
      const isJPGorPNG = file.type === 'image/jpeg' || file.type === 'image/png'; // 校验文件类型是否为JPEG或PNG格式
      const isLt2M = file.size / 1024 / 1024 < 2; // 校验文件大小是否小于2MB

      if (!isJPGorPNG) {
        this.$message.error('上传头像图片只能是 JPG 或 PNG 格式！');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }

      // 返回是否通过校验
      return isJPGorPNG && isLt2M;
    },


    // 添加员工方法
    async saveAddEmployee() {
      const flag = await this.$http.post(`/community/employee/addEmployee/`, this.addEmployeeData)

      this.showAddModal = false;
      if (flag) {
        this.$message.success("添加成功");
      }
    },

    // 修改状态方法
    async updateEmployeeStatus(id) {
      // 发送请求到后端，修改员工的状态
      const url = `/community/employee/updateStatus/${id}`;
      await this.$http.post(url);
    },
    handleSizeChange(newSize) {
      this.pageSize = newSize;
      this.currentPage = 1; // 重置当前页码为第1页
      this.getEmployees(); // 根据新的分页大小重新获取数据
    },
    handleCurrentChange(newPage) {
      this.currentPage = newPage;
      this.getEmployees(); // 根据新的当前页码获取数据
    },
    // 删除员工方法
    async deleteEmployee(id) {
      MessageBox.confirm('确定要删除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const url = `/community/employee/deleteEmployee/` + id;
        await this.$http.post(url);
        this.$message.success('员工删除成功');
        await this.getEmployees();

      }).catch(() => {
        // 取消删除操作 or 错误处理
        this.$message.error('已取消操作');
      });
    },
    // 编辑员工方法
    editEmployee(employee) {
      this.imageUrl = employee.avatar
      this.editEmployeeData = employee

      this.showEditModal = true; // 打开编辑员工的对话框
    },
    // 编辑后的代码
    async saveEmployee() {
      this.editEmployeeData.avatar = this.imageUrl

      // 调用网络请求方法将员工数据发送到后端
      await this.$http.post('/community/employee/editEmployee', this.editEmployeeData)
      this.$message.success("修改成功")

      // 刷新同时关闭模态框
      await this.getEmployees();
      this.showEditModal = false;
    },
    // 分配角色的保存按钮
    async saveRole() {
      // 去除重复的角色ID
      const uniqueRoles = Array.from(new Set(this.selectedRole));

      const params = {
        employeeId: this.selectedEmployee.id,
        roles: uniqueRoles
      };

      const response = await this.$http.post(`/community/employee/updateEmployeeRoles`, params);
      this.$message.success("操作成功");

      // 刷新
      await this.getEmployees();
      this.showRoleModal = false;
    },
    // 已经拥有的角色和所有角色是否相同，相同返回true
    isRoleSelected(role) {
      return this.selectedEmployee.roles.some(function (employeeRole, index) {
        return employeeRole.id === role.id;
      });
    },
    // 分配角色展示模态框方法
    assignRole(employee) {
      this.selectedEmployee = employee;
      this.selectedRole = [];

      // 如果selectedEmployee.roles存在，则填充选中角色
      if (this.selectedEmployee.roles && this.selectedEmployee.roles.length > 0) {
        this.$nextTick(() => {
          this.selectedEmployee.roles.forEach(selectedRole => {
            const index = this.roles.findIndex(role => role.id === selectedRole.id);
            if (index !== -1) {
              this.selectedRole.push(this.roles[index].id);
            }
          });
        });
      }

      this.showRoleModal = true;
    },
    // 查询员工方法
    async getEmployees() {
      const params = {
        employee: {
          name: this.form.searchText,
          status: this.form.statusFilter !== "" ? this.form.statusFilter : null
        },
        startDate: this.form.dateRange[0],
        endDate: this.form.dateRange[1],
      };

      const url = `/community/employee/getEmployees/${this.currentPage}/${this.pageSize}`;
      const response = await this.$http.post(url, params);

      this.filteredData = response.data.list;
      this.filteredRoleData = this.filteredData.roles
      this.total = response.data.total; // 设置总条数

    },
    // 查询所有角色
    async getRoles() {
      const response = await this.$http.get(`/community/role/getRoleList`);
      this.roles = response.data;
    }

  },
}
</script>

<style>
.flex-container {
  display: flex;
  align-items: center;
}

.search-label {
  margin-right: 8px;
  white-space: nowrap;
}

.my-dialog .dialog-content {
  padding: 20px;
  background-color: #f4f4f4;
}

.my-dialog .role-options {
  margin-top: 10px;
}

.my-dialog .dialog-footer {
  margin-top: 20px;
  text-align: right;
}

.avatar {
  width: 200px;
  height: 200px;
}
</style>